package com.css.fxfzypg.modules.baseData.repository.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.constants.FxfzConstants;
import com.css.fxfzypg.constants.YNEnum;
import com.css.fxfzypg.modules.model.entity.RescueForceEntity;
import com.css.fxfzypg.modules.baseData.repository.RescueForceRepository;
import com.css.fxfzypg.modules.model.vo.RescueForceVO;
import com.css.fxfzypg.modules.preassesstaskmanage.entity.PreAssessTaskEntity;
import com.css.fxfzypg.modules.preassesstaskmanage.repository.PreAssessTaskRepository;
import com.css.fxfzypg.util.CreateGson;
import com.css.fxfzypg.util.PlatformObjectUtils;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.entity.SUser;
import com.css.fxfzypg.zcpt.sys.service.SUserService;
import com.css.fxfzypg.zcpt.sys.service.SysAreaService;
import com.css.fxfzypg.zcpt.sys.service.SysRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author
 * @date 2022/9/28 14:33
 * @description
 **/
@Repository
public class RescueForceRepositoryImpl implements RescueForceRepository {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Autowired
    SysRoleService sysRoleService;

    @Autowired
    SUserService sUserService;

    @Resource
    private SysAreaService areaService;

    @Resource
    private PreAssessTaskRepository preAssessTaskRepository;

    @Override
    public Map<String, Object> getPage(RescueForceVO rescueForceVO, int curPage, int pageSize) {
        StringBuilder sql = new StringBuilder("select * from rescue_force_assessment");
        StringBuilder whereSql = new StringBuilder(" where del_flag = '0' ");
        StringBuilder orderSql = new StringBuilder(" order by is_default desc,province_code");
        int firstIndex = (curPage - 1) * pageSize;
        int lastIndex = pageSize;

        StringBuilder str = new StringBuilder("");
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        String role = sysRoleService.getRoleByUserId(userId);
        List<Map> roleMaps = JSONObject.parseArray(role, Map.class);
        for (Map roleMap : roleMaps) {
            str.append(roleMap.get("roleCode") + ",");
        }
        String roles = str.toString();
        if (!roles.contains(FxfzConstants.YPG_COUN_YW_ROLE) && !roles.contains(FxfzConstants.YPG_COUN_GL_ROLE)) {
            whereSql.append(" and (org_name = '系统默认' or province='" + sUser.getProvinceId() + "')");
        }

        StringBuilder limitSql = new StringBuilder(" limit " + lastIndex + " offset " + firstIndex);
        if (!PlatformObjectUtils.isEmpty(rescueForceVO.getModelName())) {
            whereSql.append(" and model_name like '%" + rescueForceVO.getModelName() + "%'");
        }
        if (!PlatformObjectUtils.isEmpty(rescueForceVO.getProvince())) {
            if ("cd726776c7de41e4a41dcdb3d90b2806".equals(rescueForceVO.getProvince()) || "225ac763ab714524b87d95140a93a4a5".equals(rescueForceVO.getProvince()) || "8a3f7d3f78ad456f92f487a979091c7f".equals(rescueForceVO.getProvince()) || "afcbf07008a34c2e85917cfd34008033".equals(rescueForceVO.getProvince())) {
                //拿到北京上海天津重庆四省的省id
                String pid = areaService.getParentId(rescueForceVO.getProvince());
                rescueForceVO.setProvince(pid);
            }
            whereSql.append(" and province = '" + rescueForceVO.getProvince() + "'");
        }
        if (!PlatformObjectUtils.isEmpty(rescueForceVO.getCity())) {
            whereSql.append(" and (city like '%" + rescueForceVO.getCity() + "%' or city = '全部')");
        }

        sql.append(whereSql).append(orderSql);
        Integer total = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(RescueForceEntity.class)).size();
        List<RescueForceEntity> list = jdbcTemplate.query(sql.append(limitSql).toString(), new BeanPropertyRowMapper<>(RescueForceEntity.class));
        Map<String, Object> map = new HashMap();
        map.put("total", total);
        map.put("rows", list);
        return map;
    }

    @Override
    public void save(RescueForceEntity rescueForceEntity) {
        String sql = "insert into rescue_force_assessment" +
                " values(:id, :modelName, :isDefault, :province, :city, :orgId, :orgName, :rescueRanksModelNumber1, " +
                ":rescueRanksModelNumber2, :rescueRanksModelNumber3, :majorRescueForceProportion, :popularRescueForceProportion, " +
                ":societyOtherForceProportion, :medicalStaffModelNumber, :doctorProportion, :nurseProportion, :psychologistProportion, " +
                ":createUser, :createUserName, :createTime, :updateUser, :updateTime, :delFlag,:provinceCode)";
        SqlParameterSource source = new BeanPropertySqlParameterSource(rescueForceEntity);
        namedParameterJdbcTemplate.update(sql, source);
    }

    @Override
    public RescueForceEntity getModelById(String id) {
        String sql = "select * from rescue_force_assessment where id = ? and del_flag = '" + YNEnum.N.toString() + "'";
        RescueForceEntity RescueForce = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(RescueForceEntity.class), id);
        return RescueForce;
    }

    @Override
    public RescueForceEntity getDefaultModel() {
        String sql = "select * from rescue_force_assessment where del_flag = '" + YNEnum.N.toString() +
                "' and is_default='" + YNEnum.Y.toString() + "' limit 1";
        return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(RescueForceEntity.class));
    }

    @Override
    public List<RescueForceEntity> getByDivision(String province, String city, int isNa) {
        String sql = "select * from rescue_force_assessment where del_flag ='" + YNEnum.N.toString() + "' and province='" + province + "'";
        if (PlatformObjectUtils.isNotEmpty(city)) {
            sql = sql + " and city='" + city + "'";
        }
        sql = sql + " order by create_time desc ";
        if (isNa == 0) {
            sql = sql + " limit 1 ";
        }
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(RescueForceEntity.class));
    }

    @Override
    public void delete(String id) {
        String sql = "update rescue_force_assessment set del_flag= '" + YNEnum.Y.toString() + "' where id = ?";
        jdbcTemplate.update(sql, id);
    }

    @Override
    public void update(RescueForceEntity rescueForce) {
        String sql = "update rescue_force_assessment set model_name = :modelName ,org_id = :orgId " +
                ",org_name = :orgName ,rescue_ranks_model_number1= :rescueRanksModelNumber1 ,rescue_ranks_model_number2 = :rescueRanksModelNumber2 " +
                ",rescue_ranks_model_number3 = :rescueRanksModelNumber3 ,major_rescue_force_proportion = :majorRescueForceProportion " +
                ",popular_rescue_force_proportion = :popularRescueForceProportion ,society_other_force_proportion = :societyOtherForceProportion " +
                ",medical_staff_model_number = :medicalStaffModelNumber ,doctor_proportion = :doctorProportion ,nurse_proportion = :nurseProportion " +
                ",psychologist_proportion = :psychologistProportion ,update_user = :updateUser ,update_time = :updateTime where id = :id";
        SqlParameterSource source = new BeanPropertySqlParameterSource(rescueForce);
        namedParameterJdbcTemplate.update(sql, source);
    }

    @Override
    public RescueForceEntity getDefaultModel(String taskId) {
        PreAssessTaskEntity preAssessTaskEntity = preAssessTaskRepository.findById(taskId);
        if (PlatformObjectUtils.isNotEmpty(preAssessTaskEntity)) {
            String taskDistrict = preAssessTaskEntity.getTaskDistrict();
            if (StringUtils.isNotBlank(taskDistrict)) {
                List<String> areaList = Arrays.asList(taskDistrict.split("、"));
                try {
                    //山东省-济宁市-金乡县
                    if (!PlatformObjectUtils.isEmpty(areaList)) {
                        for (String area : areaList) {
                            String idConcat = getAreaIdByName(area);
                            if (StringUtils.isNotBlank(idConcat)) {
                                RescueForceEntity rescueForce = getFirstRescueForce(idConcat);
                                if (rescueForce != null) {
                                    return rescueForce;
                                }
                            }
                        }
                    } else {
                        return null;
                    }
                } catch (Exception e) {
                    throw new RuntimeException("模型查询失败");
                }
            }
        }
        return null;
    }

    @Override
    public Integer countByProvince(String province) {
        return jdbcTemplate.queryForObject("SELECT count(*) from rescue_force_assessment where province = '" + province + "' and del_flag ='0' ", Integer.class);
    }

    @Override
    public Integer countByYearPrefixLike(String taskYear, String currProvinceId) {
        return jdbcTemplate.queryForObject("SELECT count(*) FROM rescue_force_assessment where (TO_CHAR(create_time, 'yyyy-MM-dd hh24:mi:ss') LIKE '" + taskYear + "%' or TO_CHAR(update_time, 'yyyy-MM-dd hh24:mi:ss') LIKE '" + taskYear + "%') and province = '" + currProvinceId + "' and del_flag ='0' ", Integer.class);
    }

    /**
     * 查询指定省和市名称对应的的id 用_分割
     */
    private String getAreaIdByName(String area) throws UnsupportedEncodingException {
        String[] split = area.split("-");
        //省
        String province = URLEncoder.encode(split[0], "UTF-8");
        String city = "";
        if (split.length > 1) {
            //市
            city = URLEncoder.encode(split[1], "UTF-8");
            //根据区域名称获取id
        } else {
            city = URLEncoder.encode("-1", "UTF-8");
        }
        //区县并不关注填充-1只是为了指定方法接收并不为空
        String country = URLEncoder.encode("-1", "UTF-8");
        return areaService.getIdByCondition(province, city, country);
    }

    /**
     * 返回第一个符合条件的模型信息
     */
    private RescueForceEntity getFirstRescueForce(String idConcat) {
        String[] idSplit = idConcat.split("_");
        String provinceId = idSplit[0];
        String cityId = idSplit[1];
        //查询该省市下的人员伤亡模型
        List<RescueForceEntity> casualties = getRescueForceByProvinceAndCity(provinceId, cityId);
        if (casualties.size() > 0) {
            return casualties.get(0);
        }
        return null;
    }

    /**
     * 查询指定省和市下的人员伤亡的模型信息
     */
    private List<RescueForceEntity> getRescueForceByProvinceAndCity(String provinceId, String cityId) {
        StringBuilder builder = new StringBuilder("select * from rescue_force_assessment where del_flag ='" + YNEnum.N.toString() + "'");
        builder.append(" and province='").append(provinceId).append("'");
        builder.append(
                " and (position('").append(cityId).append("' in city) > 0 or city='全部')");
        builder.append(" order by create_time desc");
        return jdbcTemplate.query(builder.toString(), new BeanPropertyRowMapper<>(RescueForceEntity.class));
    }
}
